<template>
  <v-card
    min-height="875"
    loader-height
  >  
    <div
      class="float-left"
      min-height="875"
    >
      <v-navigation-drawer
        v-model="drawer"
        :mini-variant.sync="mini"
        permanent
        height="875"
        width="300"
      >
        <div
          with="100%"
          height="100%"
          min-width="318px"
        >       
          <div height="60">
            <v-list-item class="px-2">
              <v-app-bar-nav-icon></v-app-bar-nav-icon>

              <v-list-item-title @contextmenu.prevent="newSpace">
                <!-- <v-select
                  v-model="space"
                  class="text-h5"
                  :items="selectItems"
                  v-on:change="selectSpace"
                  style="margin-top:10px;height:70px"
                ></v-select> -->
                <v-overflow-btn
                  v-model="space"
                  :items="selectItems"
                  v-on:change="selectSpace"
                  dense
                  
                ></v-overflow-btn>
              </v-list-item-title>
              
              <v-btn
                icon
                @click="mini=!mini"
              >
                <v-icon>mdi-chevron-left</v-icon>
              </v-btn>
            </v-list-item>

            <div class="text-center">
              <v-dialog
                v-model="spaceDialog"
                width="500"
              >
                <v-card>
                  <v-card-title class="text-h6 grey lighten-2">
                    输入子空间名称
                  </v-card-title>

                  <div style="margin-left:50px;margin-right:50px">
                  <v-text-field
                    v-model="spaceName"
                    :counter="20"
                    label="名称"
                  ></v-text-field>
                  </div>

                  <v-divider></v-divider>

                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                      color="primary"
                      text
                      @click="spaceDialog = false"
                    >
                      取消
                    </v-btn>
                    <v-btn 
                      color="primary" 
                      @click="buildSpace"
                    >
                      创建
                    </v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </div>
          </div>

          <v-divider></v-divider>
          <template>
            <v-treeview
                v-model="tree"
                :open="initiallyOpen"
                :items="items"
                activatable
                item-key="name"
                open-on-click
                dense
            >
              <template v-slot:prepend="{ item, open }">
                  <v-icon v-if="item.user">
                      mdi-account
                  </v-icon>
                  <v-icon v-if="!item.file && !item.user">
                      {{ open ? 'mdi-folder-open' : 'mdi-folder' }}
                  </v-icon>
                  <v-icon v-else>
                      {{ files[item.file] }}
                  </v-icon>
              </template>
              <template v-slot:label="{item}">
                <span 
                v-text="item.name" 
                @click="view(item)" 
                width="100%"
                >
                </span>
              </template>
              <template v-slot:append="{item}">
                <v-menu
                  bottom
                  offset-y
                  min-width='100'
                  style="z-index:99"
                >
                  <template v-slot:activator="{ on, attrs }">
                    <v-icon
                      small
                      class="ma-2"
                      v-bind="attrs"
                      v-on="on"
                    >
                      mdi-dots-vertical
                    </v-icon>
                  </template>
                  <v-list>
                    <p v-if="item.file==='md'"><button text @click="editFile(item)"><v-icon>mdi-circle-edit-outline</v-icon>编辑</button></p>
                    <p v-if="item.file==='xlsx'"><button text @click="editFile(item)"><v-icon>mdi-circle-edit-outline</v-icon>单独编辑</button></p>
                    <p v-if="!item.file"><button text @click="newBuild(item)"><v-icon>mdi-plus-thick</v-icon>新建</button></p>
                    <!-- <p v-if="item.file"><button text @click="uploadFile(item)"><v-icon>mdi-upload</v-icon>上传</button></p>
                    <p v-if="item.file"><button text @click="exportFile(item)"><v-icon>mdi-download</v-icon>导出</button></p> -->
                    <p><button text @click="deleteFile(item)"><v-icon>mdi-delete-outline</v-icon>删除</button></p>
                  </v-list>
                </v-menu>
              </template>
            </v-treeview>
            <!-- 弹框：新增文件或文件夹的名词 -->
            <div class="text-center">
              <v-dialog
                v-model="dialog"
                width="500"
              >
                <v-card>
                  <v-card-title class="text-h6 grey lighten-2">
                    输入新增的名称
                  </v-card-title>

                  <div style="margin-left:50px;margin-right:50px">
                    <v-row
                      align="center"
                    >
                      <v-col
                        cols="12"
                        sm="4"
                      >
                         <v-select
                          v-model="fileType"
                          class="text-h5"
                          :items="typeItems"
                          label="新增类型"
                        ></v-select>
                      </v-col>
                      <v-col
                        cols="12"
                        sm="8"
                      >
                        <v-text-field
                          v-model="fileName"
                          :counter="20"
                          label="名称"
                        ></v-text-field>
                      </v-col>
                    </v-row>
                  </div>

                  <v-divider></v-divider>

                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                      color="primary"
                      text
                      @click="dialog = false"
                    >
                      取消
                    </v-btn>
                    <v-btn 
                      color="primary" 
                      @click="subitName"
                    >
                      新建
                    </v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </div>
                        <!-- 弹框：新增文件或文件夹的名词 -->
            <div class="text-center">
              <v-dialog
                v-model="dialogUpload"
                width="500"
              >
                <v-card>
                  <v-card-title class="text-h6 grey lighten-2">
                    选择文件上传
                  </v-card-title>

                  <div style="margin-left:50px;margin-right:50px">
                    <v-file-input
                      v-model="uploadFileName"
                      accept="*"
                      label="File input"
                    ></v-file-input>
                  </div>

                  <v-divider></v-divider>

                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                      color="primary"
                      text
                      @click="dialogUpload = false"
                    >
                      取消
                    </v-btn>
                    <v-btn 
                      color="primary" 
                      @click="actUploadFile"
                    >
                      上传
                    </v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </div>
          </template>
        </div>
      </v-navigation-drawer>
    </div>

    <div>
      <!-- 右侧页面的路由 -->
      <v-main>
          <router-view :key="$route.fullPath" @fathre="initTreeDatas"/>
      </v-main>
    </div>
  </v-card>
</template>

<script>
import { defineComponent } from '@vue/composition-api'
import luckysheet from 'luckyexcel'
// import LuckyExcel from 'luckyexcel'

export default defineComponent({
  setup() {
    
  },
  data () {
    return {
      drawer: true,
      curNode: '',
      fileName: '',
      mini: false,
      dialog: false,
      dialogUpload: false,
      uploadFileName: null,
      fileType: 'dir',
      typeItems: ['dir', '.md', '.xlsx', '.txt'],
      space: 'All',
      selectItems: [
        'All',
        'ljk'
      ],
      spaceDialog: false,
      spaceName: '',
      initiallyOpen: ['common', 'ljk'],
      files: {
          html: 'mdi-language-html5',
          js: 'mdi-nodejs',
          json: 'mdi-code-json',
          md: 'mdi-language-markdown',
          pdf: 'mdi-file-pdf',
          png: 'mdi-file-image',
          txt: 'mdi-file-document-outline',
          xlsx: 'mdi-file-excel',
          properties: 'mdi-file-document-outline',
      },
      tree: [],
      items: [
        {
        name: 'ljk',
        user: 'ljk',
        children: [
            {
            name: 'static',
            children: [{
                name: 'web01.md',
                file: 'md',
              }],
            },
            {
            name: 'interface.md',
            file: 'md',
            },
            {
            name: 'index.xlsx',
            file: 'xlsx',
            },
        ],
        },
      ],
      dataSheets: [],
      content: ''
    }
  },
  mounted(){
    this.$emit("changeTaskID", 2)
    this.initTreeDatas()
    this.initSpaceList()
  },

  methods: { 
    initSpaceList: function(){
      console.log('initSpaceList')
      let post_data = {'type': this.space}
      this.$api.doc.getSpaces(post_data).then(res=>{
        console.log(res)
        this.selectItems = res.data.data
      })
    },
    initTreeDatas: function(){
      console.log('initTreeDatas')
      let post_data = {'space': 'All'}
      this.$api.doc.getFiles(post_data).then(res=>{
        console.log(res)
        this.items = res.data.data
      })
    },  
    selectSpace: function(e){
      console.log(e)
      let post_data = {'space': this.space}
      this.$api.doc.getFiles(post_data).then(res=>{
        console.log(res)
        this.items = res.data.data
      })
    },  
    buildSpace: function(){
        console.log('build Space')
        let post_data = {'space': this.spaceName}
        this.$api.doc.insertSpace(post_data).then(res=>{
          console.log(res)
          this.spaceDialog = false
          this.initSpaceList()
          this.initTreeDatas()
        })
      },
    newSpace: function(){
      console.log('creat space')
      this.spaceDialog = true
      this.spaceName = '' 
      console.log(this.newSpace)
    },           
    subitName: function(){
      console.log('subitName')
      console.log(this.fileName)
      let post_data = {'type': this.fileType, 'fileName': this.fileName, 'node': this.curNode}
      this.$api.doc.insertFile(post_data).then(res=>{
        console.log(res)
        this.dialog = false
        this.initTreeDatas()
      })
    },
    newBuild: function(node){
      console.log('new build')
      this.dialog = true
      this.fileName = ''
      this.curNode = node.name
      console.log(node.name)
      console.log(this.dialog)
    },
    exportFile: function(node){
      console.log('export File')
      console.log(node)
    },
    view: function(node){
      this.$router.push({ name: 'OtherPage', params:{name: node.name} });
      console.log(node)
      switch(node.file){
        case 'md' :
          console.log('md');
          this.$router.push({ name: 'ViewMD', params:{name: node.name} });
          break;
        case 'xlsx' : 
          console.log('xlsx');
          this.$router.push({ name: 'Luckysheet', params:{name: node.name, common: true} });
          console.log("init open luckysheet")
          break;
        case 'png': 
          console.log('png');
          this.$router.push({ name: 'ViewPicture', params:{name: node.name} });
          break;
        default:
          console.log('error, show default');
          this.$router.push({ name: 'OtherPage', params:{name: node.name} });
          break;
      }
    },
    viewFile: function(node) {
        console.log('click action')
        console.log(node)
        this.$router.push({ name: 'ViewMD' });
    },
    uploadFile: function(node){
      console.log('uploadFile')
      this.curNode = node
      console.log(this.curNode)
      this.dialogUpload = true
    },
    actUploadFile: function(){
      console.log('actUploadFile')
      console.log(this.uploadFileName)
      let fileT = this.curNode.file
      let fileN = this.curNode.name
      if(fileT==='xlsx'){
        console.log('get excel data...')
        this.uploadExcel(this.uploadFileName, fileN)
      }else{
        console.log('upload file...')
        console.log(fileN)
      }
    },
    uploadExcel(files, nodeName){
      let name = files.name;
      let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
      if(suffix!="xlsx"){
          alert("Currently only supports the import of xlsx files");
          return;
      }
      
      luckysheet.transformExcelToLucky(files, function(exportJson, luckysheetfile){
        console.log(exportJson)
        console.log(luckysheetfile)
        if(exportJson.sheets==null || exportJson.sheets.length==0){
            alert("Failed to read the content of the excel file, currently does not support xls files!");
            return;
        }
        let sheetdata = exportJson.sheets
        let post_data = {'filename': nodeName, 'data': sheetdata}
        this.$api.doc.uploadExcelData(post_data).then(res=>{
          console.log(res)
          this.dialogUpload = false
        })
      });
    },
    deleteFile: function(node){
      console.log('deleteFile')
      console.log(node)
      let filename = node.name
      if(confirm('确认删除节点：'+filename)){
        this.$api.doc.deleteFile({'filename': filename}).then(res=>{
          console.log(res)
          if(res.data.code===1){
            this.initTreeDatas()
          }
        })
      }
    },
    editFile: function(node){
      console.log('editFile ....')
      console.log(node)
      let fileT = node.file
      switch (fileT) {
        case 'md':
          this.$router.push({ name: 'EditMD', params:{name: node.name} });
          break
        case 'xlsx':
          this.$router.push({ name: 'Luckysheet', params:{name: node.name, common: false} });
          break
        default:
          console.log('error, show default');
          this.$router.push({ name: 'OtherPage', params:{name: node.name} });
          break;
      }

    }
  }
})
</script>

<style scoped>

</style>
